/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.reserveView;
/**
 * 说明：
 * 仓库调拨
 * @Author：
 * @Date：2012-03-21
 */
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableCellEditor;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TBillDetail;
import com.ruipengkj.bean.TStock;
import com.ruipengkj.bean.TStockInOut;
import com.ruipengkj.bean.TStore;
import com.ruipengkj.bean.TStoreTransfer;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JComboBoxPOJO;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.RPJButtonRoundBlue;
import com.ruipengkj.component.RPJButtonRoundOrager;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.comboBox.CommodityJComboBoxTableComponent;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.component.jpanel.RepeatImagePanel;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.StoreTransferDetailModel;
import com.ruipengkj.service.TBillDetailService;
import com.ruipengkj.service.TCommodityService;
import com.ruipengkj.service.TStockInOutService;
import com.ruipengkj.service.TStockService;
import com.ruipengkj.service.TStoreService;
import com.ruipengkj.service.TStoreTransferService;

public class StoreTransferPanelAddDialog extends IDialog implements TableModelListener{
	private static final long serialVersionUID = 1L;
	private JLabelJTextFieldComponent numberTF;//调拨编号
	private JLabelJComboBoxComponent outReserve;//调出仓库下拉框
	private JLabelJComboBoxComponent inReserve;//调入仓库
	
	private JLabelJTextFieldComponent numTF;//数量
	private JLabelJTextFieldComponent moneyTF;//金额
	private JLabelJTextFieldComponent storageQuantityTF;//当前库存量
	
	private JButton addButton; //添加行
	private JButton delButton; //删除行
	private JButton saveExitButton; //保存退出
	private JButton saveButton; //保存新增
	private JButton exitButton; //直接退出
	
	private JTable table;
	private JScrollPane tableJsp;
	private StoreTransferDetailModel storeTransferDetailModel;
	private TStoreService tStoreService;//仓库操作对象
	private TStoreTransferService tStoreTransferService;//仓库调拨对象
	private TBillDetailService billDetailService;//订单详细操作对象
	private TStockService tStockService;//库存
	private TStockInOutService tStockInOutService;//出入库单
	private TCommodityService tCommodityService;
	
	private CommodityJComboBoxTableComponent cbox;
	
	public boolean isSuccess=false;
	private int select = 0;
	public StoreTransferPanelAddDialog(JDialog jd, String title, boolean b) {
		super(jd, title, b);
		tCommodityService = BuildSpringApplication.getInstance().getTCommodityServiceImpl();
		tStockInOutService = BuildSpringApplication.getInstance().getTStockInOutServiceImpl();
		tStockService = BuildSpringApplication.getInstance().getTStockServiceImpl();
		billDetailService=BuildSpringApplication.getInstance().getTBillDetailServiceImpl();
		tStoreService=BuildSpringApplication.getInstance().getTStoreServiceImpl();
		tStoreTransferService=BuildSpringApplication.getInstance().getTStoreTransferServiceImpl();
		this.init();
		this.initListener();
		this.setSize(900, 600);
		this.setLocationRelativeTo(null);
	}
	private void init() {
		storeTransferDetailModel = new StoreTransferDetailModel();
		storeTransferDetailModel.setEditable(true);
		table=uiFactory.createRPJTable(storeTransferDetailModel, this, this, 30, JLabel.CENTER);
		cbox = new CommodityJComboBoxTableComponent();
		cbox.setBorder(null);
		TableCellEditor edt = new DefaultCellEditor(cbox);
		table.getColumnModel().getColumn(2).setCellEditor(edt);
		table.getColumnModel().getColumn(3).setCellEditor(edt);
		tableJsp=uiFactory.createJScrollPane(table);
		JPanel main_jp=new BorderJPanel(new BorderLayout());
		main_jp.setBackground(Util.PANEL_COLOR);
		main_jp.add(this.initTop(), BorderLayout.NORTH);
		main_jp.add(tableJsp, BorderLayout.CENTER);
		main_jp.add(this.initTail(), BorderLayout.SOUTH);
		this.add(main_jp);
		main_jp.setCursor(Util.CURSOR_DEFAULT);
		TabelUtil.hideTableColumn(0, table);
	}
	
	private JPanel initTop() {
		JPanel jp1=uiFactory.createFlowJPanel(FlowLayout.LEFT);
		numberTF= new JLabelJTextFieldComponent("调拨编号：", 30);
		numberTF.getText().setText(UUID.GenUUID15());
		numberTF.getText().setEditable(false);
		JLabelJTextFieldComponent nameTF = new JLabelJTextFieldComponent("操作人：", 30);
		nameTF.getText().setText(ApplicationContext.OPERATOR_NAME);
		nameTF.getText().setEditable(false);
		jp1.add(numberTF);
		jp1.add(nameTF);
		
		JPanel jp2=uiFactory.createFlowJPanel(FlowLayout.LEFT);
		outReserve = new JLabelJComboBoxComponent("调出仓库：", new String[]{}, 99);
		inReserve = new JLabelJComboBoxComponent("调入仓库：",  new String[]{}, 99);
		jp2.add(outReserve);
		jp2.add(inReserve);
		
		JPanel top_panel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_2).getImage());
		top_panel.setLayout(new GridLayout(2, 1));
		top_panel.add(jp1);
		top_panel.add(jp2);
		return top_panel;
	}
	
	private JPanel initTail() {
		JPanel tail_panel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_2).getImage());
		tail_panel.setLayout(new GridLayout(2, 1));
		
		JPanel jp8 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		addButton = new RPJButtonRoundBlue("添加行");
		delButton = new RPJButtonRoundOrager("删除行");
		jp8.add(addButton);
		jp8.add(delButton);
		
		JPanel jp1 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		numTF = new JLabelJTextFieldComponent("合计：数量", 10);
		numTF.getText().setText("0");
		numTF.getText().setEditable(false);
		moneyTF = new JLabelJTextFieldComponent("金额：", 10);
		moneyTF.getText().setText("0.0");
		moneyTF.getText().setEditable(false);
		storageQuantityTF = new JLabelJTextFieldComponent("当前库存量：", 10);
		storageQuantityTF.getText().setText("0");
		storageQuantityTF.getText().setEditable(false);
		jp1.add(numTF);
		jp1.add(moneyTF);
		jp1.add(storageQuantityTF);
		
		saveExitButton = new RPJButtonWhite("保存退出(Ctrl+S)");
		saveButton = new RPJButtonWhite("保存新增(Ctrl+I)");
		exitButton = new RPJButtonWhite("直接退出(Ctrl+Q)");
		jp1.add(saveExitButton);
		jp1.add(saveButton);
		jp1.add(exitButton);
		
		tail_panel.add(jp8);
		tail_panel.add(jp1);
		return tail_panel;
	}
	private void initListener(){
		addButton.addActionListener(this);
		delButton.addActionListener(this);
		saveExitButton.addActionListener(this); //保存退出
		saveExitButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		saveButton.addActionListener(this); //保存新增
		saveButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		exitButton.addActionListener(this); //直接退出
		exitButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_Q, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		outReserve.getBox().addActionListener(this);
		storeTransferDetailModel.addTableModelListener(this);
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==addButton){
			//添加行
			if (outReserve.getBox().getSelectedIndex() == 0) {
				JOptionPane.showMessageDialog(null, "请先选择调出仓库！");
				return;
			}
			if (inReserve.getBox().getSelectedIndex() == 0) {
				JOptionPane.showMessageDialog(null, "请先选择调入仓库！");
				return;
			}
			TBillDetail detail=new TBillDetail();
			detail.setDetailID(UUID.GenUUID15());
			detail.setBillID(numberTF.getText().getText().trim());
			detail.setNum(1);
			detail.setBillType(ApplicationContext.BILL_BILLTYPE7);
			storeTransferDetailModel.addBillDetail(detail);
			TableCellEditor edt = new DefaultCellEditor(cbox);
			table.getColumnModel().getColumn(2).setCellEditor(edt);
			table.getColumnModel().getColumn(3).setCellEditor(edt);
		}else if(e.getSource()==delButton){
			//删除行
			if(table.getRowCount()==0){
				JOptionPane.showMessageDialog(null, "当前数据为空");
				return;
			}else{
				List<Integer> ints=new ArrayList<Integer>();
				int select[] = table.getSelectedRows();
				if (select != null && select.length != 0) {
					for (int i = 0; i < select.length; ++i) {
						ints.add(select[i]);
					}
				}
//				for(int i=0;i<storeTransferDetailModel.findAllBillDetailList().size();i++){
//					TBillDetail billDetail=storeTransferDetailModel.findAllBillDetailList().get(i);
//					if(billDetail.isFlag()){
//						ints.add(i);
//					}
//				}
				if(ints.size()!=0){
					if(Util.showConfirmDialog("是否要删除选中行？")==0){
						for(int i=ints.size()-1;i>=0;i--){
							storeTransferDetailModel.delBillDetail(ints.get(i));
						}
					}
				}else{
					JOptionPane.showMessageDialog(null, "请先选择你需要删除的行");
				}
				ints.clear();
			}
		}else if(e.getSource()==saveExitButton){
			//保存退出
			if(this.saveStoreTransfer()){
				this.dispose();
			}
		}else if(e.getSource()==saveButton){
			//保存新增
			if(this.saveStoreTransfer()){
				numberTF.getText().setText(UUID.GenUUID15());
				outReserve.getBox().setSelectedIndex(0);
				inReserve.getBox().setSelectedIndex(0);
				storeTransferDetailModel.clearAllBillDetail();
				table.updateUI();
			}
		}else if(e.getSource()==exitButton){
			//直接退出
			if(JOptionPane.showConfirmDialog(null, "是否要退出？")==0){
				this.dispose();
			}
		} else if (e.getSource() == outReserve.getBox()) {
			if (select == 0 || select == outReserve.getBox().getSelectedIndex()) {
				select = outReserve.getBox().getSelectedIndex();
				setStore();
				return;
			}
			if (table.getRowCount() > 0) {
				if (Util.showConfirmDialog("切换仓库将会清空列表，是否切换？")==0) {
					select = outReserve.getBox().getSelectedIndex();
					storeTransferDetailModel.clearAllBillDetail();
					setStore();
					table.updateUI();
				} else {
					outReserve.getBox().setSelectedIndex(select);
				}
			}
		} else {
			super.actionPerformed(e);
		}
	}
	
	//设置条件仓库
	private void setStore(){
		if(outReserve.getBox().getSelectedIndex() != 0) {
			JComboBoxPOJO storePo=(JComboBoxPOJO)outReserve.getBox().getSelectedItem();//仓库
			cbox.settStore((TStore)storePo.getObject());
			table.updateUI();
		}
	}
	
	public void showDialog(TStoreTransfer storeTransfer){
		this.isSuccess=false;
		if (storeTransfer != null) {
			storeTransferDetailModel.setEditable(false);
			this.numberTF.getText().setText(storeTransfer.getTransferID());
			queryStore(storeTransfer.getOutStoreID(), storeTransfer.getInStoreID());
			SwingUtilities.invokeLater(queryBillDetail);
		} else {
			SwingUtilities.invokeLater(queryStore);
		}
		this.setVisible(true);
	}
	
	//数据库中的数据放入list（读取数据）
	private Runnable queryBillDetail=new Runnable() {
		@Override
		public void run() {
			try {
				addButton.setEnabled(false);
				delButton.setEnabled(false);
				saveExitButton.setEnabled(false);
				saveButton.setEnabled(false);
				TBillDetail tBillDetail = new TBillDetail();
				tBillDetail.setBillID(numberTF.getText().getText());
				tBillDetail.setBillType(ApplicationContext.BILL_BILLTYPE7);
				List<TBillDetail> billDetailList = billDetailService.findService(tBillDetail);
				if (billDetailList != null &&  billDetailList.size()!= 0) {
					int length = billDetailList.size();
					for (int i = 0; i < length; ++i) {
						//获取商品 以便查看
						billDetailList.get(i).setCommodity(tCommodityService.getByIdService(billDetailList.get(i).getCommodityID()));
						storeTransferDetailModel.addBillDetail(billDetailList.get(i));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	private void queryStore(String OutStoreID, String InStoreID) {
		try {
			if (OutStoreID != null && !OutStoreID.equals("") && InStoreID != null && !InStoreID.equals("")) {
				TStore store=tStoreService.getByIdService(OutStoreID);
				if (store != null) 
					outReserve.addElement(new JComboBoxPOJO(store.getStoreID(),store.getName(),store));
				store=tStoreService.getByIdService(InStoreID);
				if (store != null) 
					inReserve.addElement(new JComboBoxPOJO(store.getStoreID(),store.getName(),store));
				return;
			}
			outReserve.addElement(new JComboBoxPOJO("请选择仓库"));
			inReserve.addElement(new JComboBoxPOJO("请选择仓库"));
			List<TStore> list=tStoreService.findService(null);
			if(list!=null&&list.size()!=0){
				for(int i=0;i<list.size();i++){
					TStore store=list.get(i);
					outReserve.addElement(new JComboBoxPOJO(store.getStoreID(),store.getName(),store));
					inReserve.addElement(new JComboBoxPOJO(store.getStoreID(),store.getName(),store));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//查询仓库
	private Runnable queryStore=new Runnable() {
		@Override
		public void run() {
			queryStore(null, null);
		}
	};
	
	private boolean saveStoreTransfer(){
		String number=numberTF.getText().getText().trim();//编号
		if(outReserve.getBox().getSelectedIndex()==0){
			JOptionPane.showMessageDialog(null, "请选择调出仓库");
			return false;
		}
		if(inReserve.getBox().getSelectedIndex()==0){
			JOptionPane.showMessageDialog(null, "请选择调入仓库");
			return false;
		}
		JComboBoxPOJO comboBoxPOJOOut=(JComboBoxPOJO)outReserve.getBox().getSelectedItem();
		JComboBoxPOJO comboBoxPOJOIn=(JComboBoxPOJO)inReserve.getBox().getSelectedItem();
		TStore storeOut=(TStore)comboBoxPOJOOut.getObject();
		TStore storeIn=(TStore)comboBoxPOJOIn.getObject();
		if(storeOut.getStoreID().equals(storeIn.getStoreID())){
			JOptionPane.showMessageDialog(null, "调入仓库与调出仓库不可相同");
			return false;
		}
		
		List<TBillDetail> billDetailList=storeTransferDetailModel.findAllBillDetailList();
		TStock tStock = new TStock();//在仓库库存中减去相应商品的数量
		tStock.setTStore(storeOut);//库存查询条件：调出仓库
		List<TStock> tStockListOut = new ArrayList<TStock>();//储存调出仓库的库存记录
		int num = 0;//储存调出数量
		boolean okNull = false;//记录是否允许价格为空，放置消息框无限弹出
		if(billDetailList!=null&&billDetailList.size()!=0){
			for(int i=0;i<billDetailList.size();i++){
				TBillDetail tBillDetail = billDetailList.get(i);
				num += tBillDetail.getNum();
				List<TStock> list = null;//临时储存库存记录
				tStock.setTCommodity(tBillDetail.getCommodity());//库存查询条件：调出商品
				try {//根据仓库、商品查询库存
					list = tStockService.findService(tStock);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (list == null || list.size() == 0) {
					return false;
				}
				tStockListOut.add(list.get(0));
				
				if (list.get(0).getNum() < tBillDetail.getNum()) {
					JOptionPane.showMessageDialog(null, "第" + (i+1) + "件商品，在此仓库中库存不足，无法调拨！");
					return false;
				}
				
				if (tBillDetail.getCommodityID().length() == 0) {
					JOptionPane.showMessageDialog(null, "存在商品编号为空的商品！");
					return false;
				}
				if (tBillDetail.getPrice() <= 0 && !okNull) {
					if(Util.showConfirmDialog("允许商品的价格不大于零？")!=0) {
						return false;
					} else {
						okNull = true;
					}
				}
			}
		}else{
			JOptionPane.showMessageDialog(null, "请添加商品！");
			return false;
		}
		
		TStoreTransfer storeTransfer=new TStoreTransfer();
		storeTransfer.setTransferID(number);//调拨编号CHAR(15)PK
		storeTransfer.setOutStoreID(storeOut.getStoreID());//调出仓库;
		storeTransfer.setInStoreID(storeIn.getStoreID());//调入仓库
//		storeTransfer.setCommodityID("");//调拨商品编号
		storeTransfer.setNum(num);//调拨商品数量INTEGER
		storeTransfer.setOperator(ApplicationContext.OPERATOR_ID);//操作人CHAR(15)
		storeTransfer.setAuditStatu(ApplicationContext.AUDIT_STATUS3);//状态  1为正在申请2为已审核3为已完成（出库或者入库）
		storeTransfer.setAuditName("无");//审核人CHAR(15)
		storeTransfer.setAuditTime(new Date());//审核时间 
		storeTransfer.setHappenTime(new Date());
		try {
			tStoreTransferService.saveService(storeTransfer);
			tStock.setTStore(storeIn);//库存查询条件：调入仓库
			//保存销售退货详细
			for(int i=0;i<billDetailList.size();i++){
				TBillDetail tBillDetail=billDetailList.get(i);
				tBillDetail.setBillType(ApplicationContext.BILL_BILLTYPE7);
				billDetailService.saveService(tBillDetail);
				
				//在仓库库存中减去相应商品的数量 保存
				tStockListOut.get(i).setNum(tStockListOut.get(i).getNum() - tBillDetail.getNum());
				tStockService.saveOrUpdateService(tStockListOut.get(i));
				
				tStock.setTCommodity(tBillDetail.getCommodity());//库存查询条件：调入商品
				//在仓库库存中加上相应商品的数量 保存
				List<TStock> tStockListIn = tStockService.findService(tStock);
				if (tStockListIn != null && tStockListIn.size() != 0) {
					//修改数量
					TStock stock = tStockListIn.get(0);
					stock.setNum(stock.getNum() + tBillDetail.getNum());
					//修改加权价
//					stock.setAvgPrice((stock.getAvgPrice()*stock.getNum()+tBillDetail.getNum()*tBillDetail.getPrice())/(stock.getNum()+tBillDetail.getPrice()));
					tStockService.saveOrUpdateService(tStockListIn.get(0));
				} else {//如果没有相应商品记录则添加
					tStock.setStockID(UUID.GenUUID15());
					tStock.setNum(tBillDetail.getNum());
//					tStock.setAvgPrice(tBillDetail.getPrice());
					tStockService.saveService(tStock);
				}
			}

			//添加    出入库单  7为仓库调度所引起的出库，原因单为仓库调拨单
			TStockInOut tStockInOut = new TStockInOut();
			tStockInOut.setInOutID(UUID.GenUUID15());
			tStockInOut.setType((byte)1);
			tStockInOut.setSourceType((byte)7);
			tStockInOut.setTStore(storeOut);
			tStockInOut.setSource(number);
			tStockInOut.setOperator(ApplicationContext.OPERATOR_ID);
			tStockInOut.setHappenTime(new Date());
			tStockInOutService.saveService(tStockInOut);
			
			//添加  出入库单 8为仓库调度所引起的入库，原因单为仓库调拨单
			tStockInOut.setInOutID(UUID.GenUUID15());
			tStockInOut.setType((byte)1);
			tStockInOut.setSourceType((byte)8);
			tStockInOut.setTStore(storeIn);
			tStockInOutService.saveService(tStockInOut);
			
			this.isSuccess=true;
			JOptionPane.showMessageDialog(null, "操作成功");
			return true;
		} catch (Exception e) {
			this.isSuccess=false;
			e.printStackTrace();
		}
		return false;
	}
	
	public void mouseClicked(MouseEvent e) {
		if (e.getSource() == table) {
			table.updateUI();
			Object obj=table.getValueAt(table.getSelectedRow(), 2);
			if(obj!=null){
				JComboBoxPOJO storePO=(JComboBoxPOJO)inReserve.getBox().getSelectedItem();
				ApplicationContext.countStoreNumber(storeTransferDetailModel.findAllBillDetailList(), (TStore)storePO.getObject(), obj.toString(), numTF.getText(), moneyTF.getText(), storageQuantityTF.getText());
			}
		}
	}
	
	@Override
	public void tableChanged(TableModelEvent arg0) {
		int row=table.getSelectedRow();
		if(row!=-1 && row < storeTransferDetailModel.getRowCount()){
			Object obj=table.getValueAt(row, 2);
			if(obj!=null){
				JComboBoxPOJO storePO=(JComboBoxPOJO)outReserve.getBox().getSelectedItem();
				ApplicationContext.countStoreNumber(storeTransferDetailModel.findAllBillDetailList(), (TStore)storePO.getObject(), obj.toString(), numTF.getText(), moneyTF.getText(), storageQuantityTF.getText());
			}
		}
	}
}